package socketdemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server {

    private ServerSocket serverSocket;
    private List<PrintWriter> allOut = new ArrayList<>();

    public Server() {
        try {
            //创建ServerSocket对象时切记要给服务端现在要使用的端口
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端的链接");
                Socket accept = serverSocket.accept();
                System.out.println("客户端链接成功");

                Runnable r = new ClinetHandler(accept);
                Thread t = new Thread(r);
                t.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    public class ClinetHandler implements Runnable {

        private Socket socket;
        private String host;

        public ClinetHandler(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress(); //获取当前套接字实例中存放的ip地址
        }

        @Override
        public void run() {
            PrintWriter pw = null;
            try {
                //获取输入流读取数据
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                //获取输出流写出数据
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);

                //为了预防发生抢资源的情况出现 给此处代码添加同步
                synchronized (allOut) {
                    //将当前线程的输出流对象放在allOut集合当中
                    allOut.add(pw);
                    sendMessage(host + "上线啦！," + "当前在线人数" + allOut.size());
                }
                String line;
                while ((line = br.readLine()) != null) {
                    sendMessage(host + ":" + line);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //与上述synchronized代码块同理
                synchronized (allOut) {
                    allOut.remove(pw);
                    sendMessage(host + "下线啦！," + "当前在线人数" + allOut.size());
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public void sendMessage(String line) {
            //此处添加为同步块是因为 集合的遍历和增删是不可以同时进行的，如果当前线程1在对集合添加元素此时线程2正好在遍历元素，这种抢矿就会发生错误
            synchronized (allOut) {
                System.out.println(line); //在服务端输出一次
                for (PrintWriter p :
                        allOut) {
                    //将消息发送给所有客户端
                    p.println(host + ":" + line);
                }
            }
        }
    }
}
